package com.slipper.util;

import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;
import jakarta.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.crypto.SecretKey;
import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;
import java.util.Base64;
import java.util.Date;

@Component
public class JwtUtil {
    private static final String DEFAULT_SECRET_KEY = "DUR4HsdE1fWLqVmqVkXjYxW+fi9SzCrTCZ48Six5xCI=";
    private static String SECRET_KEY;

    @Value("${jwt.secret.key:#{null}}")
    private String secretKey;


    @PostConstruct
    public void init() {
        SECRET_KEY = Tool.isNotBlank(secretKey) ? secretKey : DEFAULT_SECRET_KEY;
    }

    public String createSecretKey() {
        SecureRandom random = new SecureRandom();
        byte[] keyBytes = new byte[32];
        random.nextBytes(keyBytes);
        return Base64.getEncoder().encodeToString(keyBytes);
    }

    private static SecretKey getKeyFromSecret() {
        return Keys.hmacShaKeyFor(SECRET_KEY.getBytes(StandardCharsets.UTF_8));
    }

    public static String generateToken(String subject, int days) {
        return generateToken(getKeyFromSecret(), subject, days);
    }

    public static String generateToken(SecretKey secretKey, String subject, int days) {
        long nowMillis = System.currentTimeMillis();
        Date now = new Date(nowMillis);
        Date exp = new Date(nowMillis + days * 24 * 60 * 60 * 1000L);

        return Jwts.builder()
                .issuedAt(now)
                .subject(subject)
                .expiration(exp)
                .signWith(secretKey)
                .compact();
    }

    public static String parserToken(String token) {
        return parserToken(getKeyFromSecret(), token);
    }

    public static String parserToken(SecretKey secretKey, String token) {
        return Jwts.parser()
                .verifyWith(secretKey)
                .build()
                .parseSignedClaims(token)
                .getPayload()
                .getSubject();
    }
}
